const Koa = require('koa');
const serve = require('koa-static');
const render = require('koa-ejs');
const app = new Koa();
const sqlite3 = require('sqlite3');
const {
    open
} = require('sqlite');
const path = require('path');
const {
    readFileSync
} = require('fs');

async function search(ctx) {
    var db=ctx.db;
    const word = ctx.query.word
    if (!word) {
        ctx.body = {
            errMsg: '传参错误'
        }
    } else {
        var str = `select * from dict where chinese like '%${word}%' or english like '%${word}%' or english_short like '%${word}%' `
        const data = await db.all(str);
        ctx.body = data;
    }
}
async function addWord(ctx) {
    var db=ctx.db;
    const chinese = ctx.query.chinese;
    const english = ctx.query.english;
    const english_short = ctx.query.english_short||'';
    if (!chinese) {
        ctx.body = {
            errMsg: '中文名不能为空'
        }
    }else if(!english){
        ctx.body = {
            errMsg: '英文名不能为空'
        }
    } else {
        var str = `insert into dict(chinese,english,english_short)values('${chinese}','${english}','${english_short}')`
        const data = await db.exec(str);
        ctx.body = {
            success:true
        };
    }
}
(async () => {
    // open the database
    const db = await open({
        filename: path.join(path.resolve(__dirname), './dicts.db'),
        driver: sqlite3.Database
    });
    const sqlStr = readFileSync(path.join(path.resolve(__dirname), './dict.sql'), 'utf8');
    // 移除注释
    await db.exec(sqlStr.replace(/#.*$/igm, ''));
    app.use(serve(path.join(__dirname, '.')));
    render(app, {
        root: path.join(__dirname, 'view'),
        layout: false,
        viewExt: 'html',
        cache: false,
        debug: false
    });
    app.use(async ctx => {
  
        ctx.db=db;
        if (ctx.path === '/') {
            await ctx.render('index');
        } else if (ctx.path === '/search') {
            await search(ctx);

        } else if (ctx.path === '/add') {
            await addWord(ctx);
        }


    });

    app.listen(3000);
    console.log('listen:http://localhost:3000');
})()
